//JSON字符串转JSON对象
function isJson(data){
   var json_data = null;
   var data_type = typeof(data);
   switch(data_type){
     case "string":
        try {
           json_data = JSON.parse(data);
        } catch (err){ return false; }
     break;
     case "object":
        json_data = data;
     break;
   }
	return json_data;
}

//判断是否数组
function isArray(o){
   return Object.prototype.toString.call(o)=='[object Array]';
}

//千分位格式
function Number_Format(n){
   n = n.toFixed(2);
   var num = n.toString().split('.');
   var str = num[0].replace(/(?=(?!(\b))(\d{3})+$)/g, ",");
   if(num.length > 1) str += '.' + num[1];

   return str;
}

//获取静态内容
function getHtm(action, r){
   var res;
   var rsync = r ? "?_=" + (new Date().getTime()) : "";
   var result = $.ajax({
      url      : action + rsync,
      type     : "GET",
      cache    : false,
      async    : false,
      success  : function(data){
        res = data;
      }
   });
   return res;
}

//清除html标签
function del_html_node(str){
  return str.replace(/<[^>]+>/g,"")
}


/*加载页面部分
 * 目标元素
 * htm: 页面名称
 * node: 输出到节点
 * callback: 回调函数
 * */
function loadobj(htm, node, callback){
   //if ( !node || !htm ) { return false; }
   var obj = {
      node     : node ? node : $("#Wellcome_window"),
      htm      : htm ? htm   : "login.html",
      callback : callback ? callback : null
   };

   $.ajax( {
      url     : "/" + obj.htm, //这里是静态页的地址
      type    : "GET", //静态页用get方法，否则服务器会抛出405错误
      cache   : false,
      success : function(data){
			    obj.node.html(data);
          if ( null != obj.callback) { obj.callback(); }
      }
   });
}

/* 提交修改 -- 同步
 * 提交请求会 等待返回
 * */
function getByRsync(action, dats, met){
   let res;
   if(isBrowser.ie) jQuery.support.cors=true;
   let result = $.ajax({
      url      : action,
      type     : met ? met : "POST",
      data     : dats,
      dataType : "json",
      xhrFields: {withCredentials: true},  //带cookie
      cache    : false,
      async    : false,
      success  : function(data){ res = data; }
   });
   return res;
}

/*
 * 公共异步调用函数
 * action    接口url
 * dats      提交数据
 * callback  回调函数
 * load_win  是否显示加载窗口(选传): 不传则不显示，否则显示
 */
function get_dats(action, dats, callback){
  var api_url = parent.Apps.server.url() + action;

  if(isBrowser.ie) jQuery.support.cors=true;

	$.ajax( {
      url      : api_url, //这里是静态页的地址
      type     : "POST", //静态页用get方法，否则服务器会抛出405错误
      data     : dats,
      dataType : "json",  //跨域
      xhrFields: {withCredentials: true},  //带cookie
      cache    : false,
      success  : function(data){
        if(callback) callback(data, false);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      	console.log("无法正常访问服务器，请检查网络连接");
        if(callback) callback(null, true);
      }
    });
}


//产生随机数
function randmixed(len,s) {
   let chars=s ? s.split('') : ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','0','p','q','r','s','t','u','v','w','x','y','z'];
   let res="", size = chars.length;
   let n = len > size ? size : len;
   size--;
   for(var i=0;i<n;i++){var id=Math.ceil(Math.random()*size);res+=chars[id];}
   return res;
}

/* 图片转base64 */
function getBase64(imgUrl){
      //window.URL = window.URL || window.webkitURL;
      var xhr = new XMLHttpRequest();
      xhr.open("get", imgUrl, true);
      // 至关重要
      xhr.responseType = "blob";
      xhr.onload = function () {
          if (this.status == 200) {
              var blob = this.response; //得到一个blob对象
              var oFileReader = new FileReader(); //至关重要
              oFileReader.onloadend = function (e) { var base64 = e.target.result; console.log(base64); };
              oFileReader.readAsDataURL(blob);
          }
      }
      xhr.send();
}

//判断浏览器类型
var isBrowser = function() {
    var u = navigator.userAgent;
    return {
            ie: u.indexOf('Trident') > -1, //IE内核
            opera: u.indexOf('Presto') > -1, //opera内核
            webkit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            ff: u.indexOf('Firefox') > -1, //火狐内核Gecko
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android
            iPhone: u.indexOf('iPhone') > -1 , //iPhone
            iPad: u.indexOf('iPad') > -1, //iPad
            webApp: u.indexOf('Safari') > -1 //Safari
        };
}();

//复制到粘贴板
function copyToClipBoard(copyText) {
    if (window.clipboardData) { // ie
        window.clipboardData.setData("Text", copyText);
    }
}

/*时间戳转换*/
function UnixToDateTime(unixTime,timeZone,isFull) {
   timeZone = parseInt(timeZone) || 8;
   isFull = isFull || true;
   unixTime = parseInt(unixTime) + timeZone * 60 * 60;

   var time = new Date(unixTime * 1000);
   var ymdhis = "";
   ymdhis += time.getUTCFullYear() + "-";
   ymdhis += ('0' + (time.getUTCMonth()+1)).substr(-2) + "-";
   ymdhis += ('0' + time.getUTCDate()).substr(-2);
   if (isFull === true)
   {
      ymdhis += " " + ('0' + time.getUTCHours()).substr(-2) + ":";
      ymdhis += ('0' + time.getUTCMinutes()).substr(-2) + ":";
      ymdhis += ('0' + time.getUTCSeconds()).substr(-2);
   }
   return ymdhis;
}

/* 返回当前时间 */
function getLocalTime(t){
  var timestamp = parseInt(new Date().valueOf()/1000);
  if("number" == typeof(t)){
    timestamp += t;
  }
  return UnixToDateTime(timestamp);
}

/* 返回制定日期的时间戳 */
function getTimestamp(t){
   var timestamp = 0;
   if(t){
      timestamp = parseInt(new Date(t).valueOf()/1000);
   } else {
      timestamp = parseInt(new Date().valueOf()/1000);
   }
   return timestamp;
}


/**
 * 根据日期字符串获取星期几
 * 日期字符串（如：2016-12-29），为空时为用户电脑当前日期
 */
function getWeek(dateString){
    var date;
    if(dateString == null || typeof dateString == "undefined"){
        date = new Date();
    } else {
        var dateArray = dateString.split("-");
        date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
    }
    return "星期" + "日一二三四五六".charAt(date.getDay());
}


function getQueryString(name, url) {
   var str = url ? url : window.location.search;
   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
   var r = str.substr(1).match(reg);
   if (r != null) return unescape(r[2]);
   return null;
}
